import React from "react";
import { Button, Input, Modal } from "antd";
import moment from "moment";
import { v4 as uuidv4 } from "uuid";
import "./home.scss";
import { useState, useEffect, useRef } from "react";
const ServiceCenter = () => {
  const userId =
    (localStorage.getItem("userInfo") &&
      JSON.parse(localStorage.getItem("userInfo")).userId) ||
    "";
  const socket = require("socket.io-client")("ws://localhost:3005");
  const [context, setContext] = useState("");
  const [msaList, setMsgList] = useState([]);
  const [userName, setUserName] = useState("");
  const boxRef = useRef();
  const { TextArea } = Input;

  useEffect(() => {
    let isLogin = localStorage.getItem("token");
    if (!isLogin) {
      // eslint-disable-next-line no-restricted-globals
      location.href = "/login";
    }
  }, []);

  const sendMsg = () => {
    const time = moment().format("YYYY:HH:mm");
    const msgId = uuidv4();
    let obj = {
      key: msgId,
      time,
      userId,
      msg: context,
      userName,
    };
    if (context.length > 0) socket.emit("message", obj);
    setContext("");
  };

  window.onkeydown = (e) => {
    if (e.keyCode === 13 && context != "") {
      sendMsg();
      e.preventDefault();
      e.returnValue = false;
      setContext("");
    }
  };

  const valChange = (e) => {
    setContext(e.target.value);
  };

  const saveMsg = (vals) => {
    setMsgList([...msaList, vals]);
  };

  useEffect(() => {
    socket.on("vals", saveMsg);
    boxRef.current.scrollTo(0, 1000000);
    return () => socket.off("vals", saveMsg);
  }, [msaList]);

  return (
    <>
      <div className="culmb">
        <div className="textShow" ref={boxRef}>
          {msaList.map((item) => {
            return (
              <div
                key={item.key}
                className={item.userId == userId ? "rigbox" : "lefbox"}
              >
                <div className="nameBox">
                  <div className="msgBox">{item.msg}</div>
                </div>
              </div>
            );
          })}
        </div>
        <div className="fix">
          <TextArea
            showCount
            maxLength={100}
            className="areaIpt"
            style={{ resize: "none" }}
            value={context}
            onChange={(e) => {
              valChange(e);
            }}
          />
          <div className="btnBottom">
            <Button onClick={sendMsg}>发送</Button>
          </div>
        </div>
      </div>
    </>
  );
};

export default ServiceCenter;
